package com.example.poselib

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.isseiaoki.simplecropview.FreeCropImageView
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.loader.ImageLoader
import com.lzy.imagepicker.ui.ImageGridActivity
import com.lzy.imagepicker.view.CropImageView


/**
 * 骨骼图姿势测试页面
 * 选择一个图片，输出骨骼图
 * */
class PoseTestActivity : AppCompatActivity() {

    private val TAG = "PoseTestActivity"
    private val LEFT_IMAGE_PICKER: Int = 101
    private val ROGHT_IMAGE_PICKER: Int = 102
    private val imagePicker = ImagePicker.getInstance()
    private var poseMaker: PoseMaker? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pose_test)
        VisualizationUtils.initPaint(this)
        poseMaker = PoseMaker(this)
        initData()
        initPicker()

    }

    private fun initPicker() {
        imagePicker.imageLoader = GlideImageLoader(this) //设置图片加载器
        imagePicker.isShowCamera = true //显示拍照按钮
        imagePicker.isCrop = false //允许裁剪（单选才有效）
        imagePicker.setFreeCrop(false, FreeCropImageView.CropMode.FREE) //新版添加,自由裁剪，优先于setCrop
        imagePicker.isSaveRectangle = true //是否按矩形区域保存
        imagePicker.selectLimit = 9 //选中数量限制
        imagePicker.isMultiMode = false
        imagePicker.style = CropImageView.Style.RECTANGLE //裁剪框的形状
        imagePicker.focusWidth = 800 //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.focusHeight = 800 //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.outPutX = 1000 //保存文件的宽度。单位像素
        imagePicker.outPutY = 1000 //保存文件的高度。单位像素

    }

    private fun initData() {
        findViewById<Button>(R.id.btn_out).setOnClickListener {
            finish()
        }
        findViewById<ImageView>(R.id.iv_left_image).setOnClickListener {
            Log.i(TAG, "LEFT_IMAGE_PICKER: ")
            pickerImage(LEFT_IMAGE_PICKER)
        }

        findViewById<ImageView>(R.id.iv_right_image).setOnClickListener {
            Log.i(TAG, "ROGHT_IMAGE_PICKER: ")
            pickerImage(ROGHT_IMAGE_PICKER)
        }

        findViewById<Button>(R.id.btn_left).setOnClickListener {
            Log.i(TAG, "btnLeft: ")
            val copyImage= getBitmap(findViewById<ImageView>(R.id.iv_left_image))
            val poseBitmap = poseMaker?.processImage(copyImage)
            findViewById<ImageView>(R.id.iv_left_pose).setImageBitmap(poseBitmap)
        }
        findViewById<Button>(R.id.btn_right).setOnClickListener {
            Log.i(TAG, "btnRight: ")
            val copyImage=getBitmap(findViewById<ImageView>(R.id.iv_right_image))
            val poseBitmap = poseMaker?.processImage(copyImage)
            findViewById<ImageView>(R.id.iv_right_pose).setImageBitmap(poseBitmap)
        }
        findViewById<Button>(R.id.btn_center).setOnClickListener {
            Log.i(TAG, "btnCenter: ")
            val copyStanderImage= getBitmap(findViewById<ImageView>(R.id.iv_left_image))
            val copyTargetImage= getBitmap(findViewById<ImageView>(R.id.iv_right_image))
            val result=poseMaker?.similarScore(copyStanderImage,copyTargetImage)
            val ivScoreResult=findViewById<ImageView>(R.id.iv_score_result)
            val tvScoreResult=findViewById<TextView>(R.id.tv_score_result)
            ivScoreResult.setImageBitmap(result?.resultBitmap)
            tvScoreResult.text="相似度得分： "+result?.similarScore

        }
    }

    private fun getBitmap(view:ImageView):Bitmap{
        view.isDrawingCacheEnabled = true
        val iamge = view.drawingCache
        val copyImage = iamge.copy(Bitmap.Config.ARGB_8888, true)
        view.isDrawingCacheEnabled = false
        return copyImage
    }

    private fun pickerImage(position: Int) {
        val intent = Intent(this.baseContext, ImageGridActivity::class.java)
        startActivityForResult(intent, position)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == LEFT_IMAGE_PICKER) {
                val image =
                    data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>?
                image?.let {
                    val image= findViewById<ImageView>(R.id.iv_left_image)
                    Glide.with(image).load(it[0].uri).into(image)
                }
                return
            }
            if (data != null && requestCode == ROGHT_IMAGE_PICKER) {
                val image =
                    data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>?
                image?.let {
                    val image= findViewById<ImageView>(R.id.iv_right_image)
                    Glide.with(image).load(it[0].uri).into(image)
                }
                return
            }
            Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show()
        }
    }
    private class GlideImageLoader(private val context: Context) : ImageLoader {
        override fun displayImage(
            activity: Activity,
            uri: Uri,
            imageView: ImageView,
            width: Int,
            height: Int
        ) {
            Glide.with(activity).load(uri).override(width, height).into(imageView)
        }


        override fun clearMemoryCache() {
            Glide.get(context).clearMemory()
        }

    }
}



